/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package spwpanel;

import context.Client;
import hibernate.conf.SpwHibernateUtil;
import hibernate.data.Users;
import hibernate.data.UserKinds;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author GBrdej
 */
public class UserWindow extends javax.swing.JFrame {
    
    
    /**
     * Variables - by programmer
     */
    Users user = null;
    UserKinds userKinds = null;
    ArrayList <UserKinds> userArrKinds = new ArrayList<UserKinds>();
    boolean editWindow = false;
    Client client = null;

    

    /**
     * Creates new form UserWindow
     */
    public UserWindow(Client client) {
        
        this.client = client;
        initComponents();
        
        Session session = client.getSession();
        
        List kindList = session.createCriteria(UserKinds.class).list();
        
        userArrKinds = new ArrayList<UserKinds>(kindList);
        
        for (int i=0; i<userArrKinds.size(); i++){
            
            kindBox.addItem(userArrKinds.get(i).getUksName());
        }
        
        
        if(editWindow){
            passwordField.setEnabled(false);
            passLabel.setEnabled(false);
        }
    }
    
    
    public UserWindow(Client client, Users user) {
        
        this.client = client;
        this.user = user;
        initComponents();
        
        Session session = client.getSession();
        
        List kindList = session.createCriteria(UserKinds.class).list();
        
        userArrKinds = new ArrayList<UserKinds>(kindList);
        
        for (int i=0; i<userArrKinds.size(); i++){
            
            kindBox.addItem(userArrKinds.get(i).getUksName());
            if (userArrKinds.get(i).getUksName().equalsIgnoreCase(user.getUrsKind().getUksName())){
                kindBox.setSelectedIndex(i);
            }
        }
        
        this.lastNameField.setText(user.getUrsLastName());
        this.nameField.setText(user.getUrsFirstName());
        this.mailField.setText(user.getUrsMail());
        this.loginField.setText(user.getUrsLogin());
        if(user.getUrsActive() == 'A'){
            this.activeRadio.setSelected(true);
        }else{
            this.unActiveRadio.setSelected(true);
        }
        
        
        
        
        
        if(editWindow){
            passwordField.setEnabled(false);
            passLabel.setEnabled(false);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        userActive = new javax.swing.ButtonGroup();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        nameField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        lastNameField = new javax.swing.JTextField();
        loginField = new javax.swing.JTextField();
        passwordField = new javax.swing.JTextField();
        mailField = new javax.swing.JTextField();
        kindBox = new javax.swing.JComboBox();
        activeRadio = new javax.swing.JRadioButton();
        unActiveRadio = new javax.swing.JRadioButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        passLabel = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        errorLabel = new javax.swing.JLabel();
        errName = new javax.swing.JLabel();
        errLast = new javax.swing.JLabel();
        errLogin = new javax.swing.JLabel();
        errPass = new javax.swing.JLabel();
        errMail = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        okButton.setText("Zatwierdź");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Anuluj");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("Imię:");

        userActive.add(activeRadio);
        activeRadio.setSelected(true);
        activeRadio.setText("Aktywny");

        userActive.add(unActiveRadio);
        unActiveRadio.setText("Nieaktywny");

        jLabel2.setText("Nazwisko:");

        jLabel3.setText("Login:");

        passLabel.setText("Hasło:");

        jLabel5.setText("eMail:");

        errorLabel.setForeground(new java.awt.Color(204, 0, 51));

        errName.setForeground(new java.awt.Color(204, 0, 51));

        errLast.setForeground(new java.awt.Color(204, 0, 51));

        errLogin.setForeground(new java.awt.Color(204, 0, 51));

        errPass.setForeground(new java.awt.Color(204, 0, 51));

        errMail.setForeground(new java.awt.Color(204, 0, 51));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(129, 129, 129)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(okButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancelButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(passLabel)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(activeRadio)
                            .addComponent(unActiveRadio)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(nameField)
                                    .addComponent(lastNameField)
                                    .addComponent(loginField)
                                    .addComponent(passwordField)
                                    .addComponent(mailField)
                                    .addComponent(kindBox, 0, 149, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(errLast)
                                    .addComponent(errName)
                                    .addComponent(errLogin)
                                    .addComponent(errPass)
                                    .addComponent(errMail)))))
                    .addComponent(errorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 229, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(90, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(errName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lastNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(errLast))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(loginField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(errLogin))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(passLabel)
                    .addComponent(errPass))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(mailField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(errMail))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(kindBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(activeRadio)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(unActiveRadio)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
                .addComponent(errorLabel)
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(okButton)
                    .addComponent(cancelButton))
                .addGap(37, 37, 37))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        // TODO add your handling code here:
        Users tmpUser = new Users();
        clearErrors();
        String userName = nameField.getText();
        if(userName == null || userName.equalsIgnoreCase("")){
            errorLabel.setText("Proszę podać imię użytkownika");
            errName.setText("!!");
            return;
        }else{
            tmpUser.setUrsFirstName(userName);
        }
        String userLastName = lastNameField.getText();
        if(userLastName == null || userLastName.equalsIgnoreCase("")){
            errorLabel.setText("Proszę podać nazwisko użytkownika");
            errLast.setText("!!");
            return;
        }else{
            tmpUser.setUrsLastName(userLastName);
        }
        String userLogin = loginField.getText();
        if (userLogin == null || userLogin.equalsIgnoreCase("")) {
            errorLabel.setText("Proszę podać login użytkownika");
            errLogin.setText("!!");
            return;
        }else{
            tmpUser.setUrsLogin(userLogin);
        }
        String userPassword = passwordField.getText();
        if(!editWindow && (userPassword == null || userPassword.equalsIgnoreCase(""))){
            errorLabel.setText("Proszę podać hasło użytkownika");
            errPass.setText("!!");
            return;
        }else{
            tmpUser.setUrsPassword(userPassword);
        }
        String userMail = mailField.getText();
        if(userMail == null || userMail.equalsIgnoreCase("")){
            errorLabel.setText("Proszę podać mail użytkownika");
            errPass.setText("!!");
            return;
        }else{
            tmpUser.setUrsMail(userMail);
        }
        Session session = client.getSession();
        
        
        boolean userActive = activeRadio.isSelected();
        if(userActive){
            tmpUser.setUrsActive('A');
        }else{
            tmpUser.setUrsActive('N');
        }
        
       String userKind = (String)kindBox.getSelectedItem();
       for (int i=0; i<this.userArrKinds.size(); i++){
           if(this.userArrKinds.get(i).getUksName().equalsIgnoreCase(userKind)){
               tmpUser.setUrsKind(this.userArrKinds.get(i));
               break;
           }
       }
       if(this.user != null){
            this.user.setUrsActive(tmpUser.getUrsActive());
            this.user.setUrsFirstName(userName);
            this.user.setUrsLastName(userLastName);
            this.user.setUrsLogin(userLogin);
            this.user.setUrsMail(userMail);
            session.update(this.user);
            setVisible(false);
            return;
        }
       
       
       Date userCreateDate = new Date();
       tmpUser.setUrsCreateDate(userCreateDate);
       this.user = tmpUser;
       
       session.save(this.user);
       
       
       setVisible(false);
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        // TODO add your handling code here:
        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(UserWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(UserWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(UserWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(UserWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                //new UserWindow().setVisible(true);
            }
        });
    }
    
    private void clearErrors(){
        errorLabel.setText("");
        errLast.setText("");
        errLogin.setText("");
        errMail.setText("");
        errName.setText("");
        errPass.setText("");
        
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JRadioButton activeRadio;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel errLast;
    private javax.swing.JLabel errLogin;
    private javax.swing.JLabel errMail;
    private javax.swing.JLabel errName;
    private javax.swing.JLabel errPass;
    private javax.swing.JLabel errorLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JComboBox kindBox;
    private javax.swing.JTextField lastNameField;
    private javax.swing.JTextField loginField;
    private javax.swing.JTextField mailField;
    private javax.swing.JTextField nameField;
    private javax.swing.JButton okButton;
    private javax.swing.JLabel passLabel;
    private javax.swing.JTextField passwordField;
    private javax.swing.JRadioButton unActiveRadio;
    private javax.swing.ButtonGroup userActive;
    // End of variables declaration//GEN-END:variables

    public boolean isEditWindow() {
        return editWindow;
    }

    public void setEditWindow(boolean editWindow) {
        passwordField.setEnabled(false);
        passLabel.setEnabled(false);
        this.editWindow = editWindow;
    }

    public Users getUser() {
        return user;
    }

    public void setUser(Users user) {
        this.user = user;
    }



}
